package com.fyf.game.net;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @author fanyifeng
 */
public class NioUtil
{
	public static Selector createSelector() {
		try {
			return Selector.open();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	public static SocketChannel createAsynChannel() {
		try {
			SocketChannel channel = SocketChannel.open();
			channel.configureBlocking(false);
			return channel;
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * @param port
	 * @return ssc
	 */
	public static ServerSocketChannel createAsynServerChannel(int port) {
		try {
			ServerSocketChannel ssc = ServerSocketChannel.open();
			ssc.configureBlocking(false);
			ssc.socket().bind(new InetSocketAddress(port));
			return ssc;
		} catch (IOException ex) {
			throw new RuntimeException(ex);
		}
	}

	/**
	 * @param key
	 */
	public static void cancelAndClose(SelectionKey key) {
		SelectableChannel ch = null;
		try {
			ch = key.channel();
		} catch (Exception ex) {}
		try {
			key.cancel();
		} catch (Exception ex) {}
		if (ch != null) {
			try {
				ch.close();
			} catch (Exception e) {}
		}
	}

	/**
	 * @param ch
	 */
	public static void close(SelectableChannel ch) {
		try {
			ch.close();
		} catch (Exception ex) {}
	}
}
